package com.hdu.atomic;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;

@Data
@Slf4j
public class ABAQuestionV1 {

    public static void main(String[] args) {
        AtomicStampedReference<String> atomicStampedReference = new AtomicStampedReference<>("A", 0);
        String preStr = atomicStampedReference.getReference();
        int stamp = atomicStampedReference.getStamp();
        log.info("现在版本号 : {}", stamp);
        otherChange(atomicStampedReference);
        boolean flag = atomicStampedReference.compareAndSet(preStr, "C", stamp, stamp + 1);
        if (flag) {
            log.info("修改成功");
        } else {
            log.error("修改失败");
            log.info("现在版本号 : {}", atomicStampedReference.getStamp());
        }
    }


    static void otherChange(AtomicStampedReference<String> atomicStampedReference) {
        atomicStampedReference.compareAndSet(
                "A", "B",
                atomicStampedReference.getStamp(),
                atomicStampedReference.getStamp() + 1
        );
        atomicStampedReference.compareAndSet(
                "B", "A",
                atomicStampedReference.getStamp(),
                atomicStampedReference.getStamp() + 1
        );
    }

}
